package com.myprojects.webresources.servletComponent;

import com.myprojects.webresources.service.FeignPermissionService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Iterator;

/**
 *  自定义Filter类
 */
@WebFilter(urlPatterns = {"/*"})
@Component
public class MyWebFilter implements Filter {
    private static final Logger logger = LoggerFactory.getLogger(MyWebFilter.class);

    @Autowired
    private FeignPermissionService feignPermissionService;

    private static final String ALLOWED_STRINGS[] = {
            "static",
            "login",
            "register",
            "index",
            "favicon",
            "test1",
            "test"
    };

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    /**
     * 检测accessToken是否有效
     * @param accessToken
     * @return 返回一个boolean值，true为有效，false为无效
     */
    public boolean isTokenValid(String accessToken,String requestURI){
        boolean result = false;
        System.out.println("该请求的accessToken为:"+accessToken);

        boolean b1 = accessToken instanceof String;
        System.out.println("accessToken instanceof String:"+b1);
        if (accessToken == null || "".equals(accessToken) || "null".equals(accessToken)){
            result = false;
        }else {
            //继续检查不为空的accessToken是否拥有权限
            result = feignPermissionService.checkUserRequest(accessToken, requestURI);
        }
        System.out.println("此时result为:"+result);
        return result;
    }

    /**
     * 该方法用于检查请求被允许直接或在有权限时通过过滤器
     * @return true为通过，false为仍需进行权限认证
     */
    private boolean checkIsAllowed(HttpServletRequest request){
        Iterator<String> iterator = Arrays.stream(ALLOWED_STRINGS).iterator();

        //如果请求方法为OPTIONS就直接通过
        if (request.getMethod().equals(RequestMethod.OPTIONS.name())){
            return true;
        }
        //如果请求中含有特定的允许通过的字符串，则也可以通过过滤器
        String requestURI = request.getRequestURI();
        while(iterator.hasNext()){
            String allowedString = iterator.next();
            if (requestURI.contains(allowedString)){
                return true;
            }
        }
        //如果请求链接直接为"/"则可以直接放行
        if (requestURI.equals("/"))
            return true;

        String accessToken = request.getHeader("accessToken");
        return isTokenValid(accessToken,requestURI);
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse,
                         FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        logger.info("网页请求进入访问过滤器，访问的url:{}，访问的方法：{}", request.getRequestURL(), request.getMethod());

        if (checkIsAllowed(request)){
            logger.info("请求结果：该网页请求已通过验证", request.getRequestURL(), request.getMethod());
            filterChain.doFilter(servletRequest,servletResponse);
        }else{
            logger.info("请求结果：该网页请求未通过验证", request.getRequestURL(), request.getMethod());
            // /page/reject.html
            RequestDispatcher requestDispatcher=request.getRequestDispatcher("/page/reject.html");
            requestDispatcher.forward(servletRequest, servletResponse);
        }

    }

    @Override
    public void destroy() {

    }
}
